package com.xgkj.diyiketang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.yizhibo.Constants;
import com.xgkj.diyiketang.yizhibo.PlayerActivity;
import com.xgkj.diyiketang.yizhibo.PlayerNewActivity;
import com.xgkj.eatshow.wxapi.WXEntryActivity;

import java.util.ArrayList;

/**
 * Created by XCKJ_Paladowow on 2016/7/21.
 */
public class LiveOverActivity extends BaseActivity implements View.OnClickListener{
    private Context mContext;
    private String guankanshu;
    private TextView gksText;
    private String mVid;
    private Button againBtn;
    private Button closeBtn;
    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    public static Tencent mTencent;
    private String share_title;
    private String share_path;
//    private ArrayList<EatShowUserInfo> mList;
//    private int currentPosition;
    private int from;
    private String liveState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.liveover);
        mContext = this;
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
        initView();
    }

    private void initView(){
        Intent intent = getIntent();
        guankanshu = intent.getStringExtra("NUM");
        mVid = intent.getStringExtra("VID");
        liveState = intent.getStringExtra("liveState");
        share_title = intent.getStringExtra("TITLE");
//        share_path = "http://www.chiboker.com/yzb/yzb.html?vid=" + mVid + "";
        share_path = "http://app.sjmingze.com/yzb/yzb.html?vid=" + mVid + "";
//        mList = (ArrayList<EatShowUserInfo>) getIntent().getSerializableExtra("ZHIBO_LIST");
//        currentPosition = getIntent().getIntExtra("CURRENT_POSITION",0);
        from = getIntent().getIntExtra("FROM",0);
        gksText = (TextView) findViewById(R.id.duoshaoren);
        gksText.setText(guankanshu);
        ((ImageView) findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        againBtn = (Button) findViewById(R.id.zaikanyici);
        againBtn.setOnClickListener(this);
        if (from ==1){
            againBtn.setVisibility(View.GONE);
        }
        closeBtn = (Button) findViewById(R.id.fanhuishouye);
        closeBtn.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.zaikanyici:
                Intent intent = new Intent(mContext, PlayerNewActivity.class);
                intent.putExtra(Constants.EXTRA_KEY_VIDEO_ID, mVid);
                intent.putExtra(Constants.LIVE_STATE,liveState);
//                intent.putExtra("ZHIBO_LIST", mList);
//                intent.putExtra("CURRENT_POSITION",currentPosition);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
                break;
            case R.id.fanhuishouye:
                finish();
                break;

            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                shareToWeiXin(share_path, true);
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
                shareToWeiXin(share_path, false);
                break;
            case R.id.share_to_qq:
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com:8096/liveshow/images/app_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                break;
        }

    }


    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);

            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)){

            }else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)){

            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };


    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mWeixinShareReceive != null){
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine){
            msg.title = share_title;
        }else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }
}
